package com.rcl.mvvmdemo.player

import android.util.Log
import com.rcl.mvvmdemo.lifecycle.AbsLifecycle
import com.rcl.mvvmdemo.lifecycle.ILifecycle
import com.rcl.mvvmdemo.lifecycle.LifecycleState
import com.rcl.mvvmdemo.player.domain.Music

/*
 * class title: 播放音乐 暂停音乐 上一首 下一首
 * ========================================
 * 播放状态：
 * -通过ui改变播放状态
 * -通知ui进度的变化
 * 上一首，下一首
 * -通知ui歌曲标题变化
 * -通知ui歌曲封面变化
 * 暂停音乐
 * -更新ui状态为暂停
 *
 *
 * 相关数据
 * 当前播放的歌曲
 * 当前播放的状态
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2020/11/4.
 * PS: Not easy to write code, please indicate.
 */
class PlayerPresenter private constructor() : AbsLifecycle() {

    //单例-懒加载
    companion object {
        val instance by lazy {
            PlayerPresenter()
        }
    }

    //播放的歌曲
    var currentMusic = DataListenerContainer<Music>()

    //播放的状态
    enum class PlayState {
        NONE, PLAYING, PAUSE, LOADING
    }

    var livePlayerState = LivePlayerState.instance
    var currentPlayState = DataListenerContainer<PlayState>()

    private val playerModel by lazy {
        PlayerModel()
    }

    private val player by lazy {
        MusicPlayer()
    }

    /**
     * 根据状态控制音乐播放还是暂停
     */
    fun doPlayOrPause() {
        if (currentMusic.value == null) {
            //去获取一首歌曲
            currentMusic.value = playerModel.getSongById("卡农")
        }
        player.play(currentMusic.value)
        if (currentPlayState.value != PlayState.PLAYING) {
            //开始播放音乐
            currentPlayState.value = PlayState.PLAYING
            livePlayerState.postValue(PlayState.PLAYING)
        } else {
            //暂停播放
            currentPlayState.value = PlayState.PAUSE
            livePlayerState.postValue(PlayState.PAUSE)
        }
    }

    /**
     * 播放下一首歌曲
     */
    fun playNext() {
        currentMusic.value = playerModel.getSongById("下一首：梦中的婚礼")
        //1.拿到下一首歌曲 -- >变更ui，包括标题和封面
        //2.设置给播放器
        //3.等待播放的回调通知
        currentPlayState.value = PlayState.PLAYING
    }

    /**
     * 播放上一首歌曲
     */
    fun playPre() {
        currentMusic.value = playerModel.getSongById("下一首：圣母颂")
        currentPlayState.value = PlayState.PLAYING
    }

    override fun onCreate() {

    }

    override fun onStart() {
        //监听网络状态变化
        Log.i("aaaaa", "监听网络状态变化...")
    }

    override fun onResume() {

    }

    override fun onPause() {

    }

    override fun onStop() {
        //停止监听网络状态变化
        Log.i("aaaaa", "停止监听网络状态变化...")
    }

    override fun onDestroy() {

    }

    override fun onViewLifeStateChange(state: LifecycleState) {

    }
}